package com.example.demo.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demo.common.AjaxResult;
import com.example.demo.common.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("application/json;charset=utf8");

        //获取用户传输的token用户凭证
        String token = request.getHeader("token");
        if (token == null){
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.error(401,"token不能为空")));
            return false;
        }

        try{

            //校验token合法性
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TokenService.TOKEN_SECRET)).build();
            verifier.verify(token);

            return true;//直接放行
        }catch(Exception e){
            e.printStackTrace();
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.error(401,"token不合法")));
            return false;
        }

    }

}
